//
//  TopListController.m
//  Qzone
//
//  Created by zhangxy on 2018/6/28.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "TopListController.h"


#import "TopListCell.h"
#define cellIdentifier @"TopListCell"
#import <SDWebImage/UIImageView+WebCache.h>

#import "ZZHomeTopMenu.h"
#import "UserInfoController.h"

@interface TopListController (){
    int type; // 1，2,3
    int page;
}


@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  UITableView *listTable;

@property(nonatomic,strong)  UIView *headerView;
@end

@implementation TopListController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [super viewDidLoad];
    self.navigationItem.title = @"排行榜";
    [self setNavigationBar];
    
    self.navigationController.navigationBarHidden = NO;
    
    UIImageView *bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    [bgView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    [self.view addSubview:bgView];
    ZZHomeTopMenu *menu = [[ZZHomeTopMenu alloc] initWithFrame:CGRectMake(20, 0, ScreenWidth-40,44) array:@[@"等级排行",@"土豪排行",@"人气排行"] textColor:UIColorFromRGB(TextWhiteColor) checkColor:UIColorFromRGB(TextWhiteColor) result:^(NSInteger tag, NSString *title) {
        type = tag;
        [self.listTable.header beginRefreshing];
    }];
    [menu setBackgroundColor:UIColor.clearColor];
    [self.view addSubview:menu];
    
    [self createTableView];
}


- (UIView *)headerView
{
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 163)];
    [_headerView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    
    
    return _headerView;
}

-(void)setDataToHeaderView{
    if(_listArray.count < 3){
        return;
    }
    [_headerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat itemW = 65+7;
    CGFloat space = (ScreenWidth - itemW * 3 - 80)/2;
    for(int i=0;i<3;i++){
        User *user = [_listArray objectAtIndex:i];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(40 + i*70 + space*i, 25, itemW, 110)];
        
        UILabel *lab = [self createLabel];
        [lab setFrame:CGRectMake(0, 0, 23, 22)];
        [lab setTextColor:UIColorFromRGB(TextWhiteColor)];
        [lab setFont:FontSeventeen];
        lab.layer.cornerRadius = 10.0f;
        lab.layer.masksToBounds = YES;
        lab.layer.borderColor = UIColor.whiteColor.CGColor;
        lab.layer.borderWidth = 2.0f;
        [lab setText:convertIntToString(i+1)];
        [lab setTextAlignment:NSTextAlignmentCenter];
        [lab setBackgroundColor:UIColorFromRGB(BgYellowColor)];
        
        UIImageView *imgAvatar = [self createImageView];
        [imgAvatar setFrame:CGRectMake(7, 0, 65, 65)];
        imgAvatar.layer.cornerRadius = 65.0/2;
        imgAvatar.layer.masksToBounds = YES;
        [imgAvatar sd_setImageWithURL:[NSURL URLWithString:user.user_avatar]];
        
        UILabel *labName = [self createLabel];
        [labName setFrame:CGRectMake(7, 70, 65, 24)];
        [labName setTextColor:UIColorFromRGB(TextWhiteColor)];
        [labName setFont:FontSeventeen];
        [labName setTextAlignment:NSTextAlignmentCenter];
        [labName setText:user.user_name];
        [labName setBackgroundColor:UIColor.clearColor];
        
        
        UIButton *btn = [self createButton];
        [btn setFrame:CGRectMake(7, 105, 65, 16)];
        [btn.titleLabel setFont:ListElevenFont];
        btn.layer.cornerRadius = 4;
        btn.layer.masksToBounds = YES;
        btn.layer.borderColor = UIColorFromRGB(BorderLineColor).CGColor;
        btn.layer.borderWidth = 1.0f;
        [btn setTitleColor:UIColorFromRGB(TextSizeOneColor) forState:0];
        [btn setImage:[UIImage imageNamed:@"btn_heat"] forState:0];
        if(type == 1){
            [btn setTitle:user.count_view forState:0];
        }
        else if(type == 2){
            [btn setTitle:user.user_gold forState:0];
        }else{
            [btn setTitle:user.now_value forState:0];
        }
        [view addSubview:imgAvatar];
        [view addSubview:lab];
        [view addSubview:labName];
        [view addSubview:btn];
        
        
        view.tag = i;
        view.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [view addGestureRecognizer:tap];
        
        [_headerView addSubview:view];
        
    }
}


-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:CGRectMake(0, 44, ScreenWidth, self.view.bounds.size.height - 44)];
    
    [_listTable setBackgroundColor:[UIColor whiteColor]];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    _listTable.tableHeaderView = [self headerView];
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    
    [self setTableSeparatorInset];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadBegin];
    }];
    header.stateLabel.hidden=YES;
    header.lastUpdatedTimeLabel.hidden=YES;
    _listTable.header = header;
    type = 1;
    [self loadBegin];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

-(void)loadBegin{
    page = 1;
    [self loadMoreData];
}

/**
 加载更多
 */
-(void)loadMoreData{
    NSString *api = API_GetTopList;
    if(type == 3){
        api = API_GetTopListDaren;
    }
    
    NSDictionary *p = @{@"sort_type":@"like",@"time_type":@"all",@"page":convertIntToString(page)};
    if(type == 2){
        p = @{@"sort_type":@"view",@"time_type":@"all",@"page":convertIntToString(page)};
    }
    if(type == 3){
//        p = @{@"nav_type":@"like",@"page":convertIntToString(page)};
    }
    [NetworkUtil POST:api parameters:p success:^(id responseObject, NSDictionary *dictionary) {
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        if(page == 1){
            [self.listArray removeAllObjects];
        }
        NSArray *arr = nil;
        if([dictionary[@"data"] isKindOfClass:[NSDictionary class]]){
            arr = dictionary[@"data"][@"list"];
        }else{
            arr = dictionary[@"data"][0][@"list"];
        }
        
        for(NSDictionary *item in arr){
            [self.listArray addObject:[[User alloc] initWithDictionary:item]];
        }
        [self.listTable reloadData];
       
    } failure:^(NSError *error, NSString *message) {
        [PopUtil showMessage:message];
    }];
}

-(void)tapClick:(UITapGestureRecognizer *) tap{
    int tag = (int)tap.view.tag;
    [self goUserInfo:tag];
}



#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    if(section == 0){
        [self setDataToHeaderView];
    }
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count-3;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TopListCell *cell = (TopListCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[TopListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.type = type;
    [cell dataToView:[_listArray objectAtIndex:indexPath.row + 3] row:indexPath.row];
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self goUserInfo:indexPath.row+3];
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.row+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}

-(void)goUserInfo:(int ) index{
    User *user = [_listArray objectAtIndex:index];
    UserInfoController *vc = [[UserInfoController alloc] init];
    vc.user_id = user.user_id;
    [self openPushVC:vc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
